<!-- 顶部 toolbar -->
<template>
  <div>
    <div class="fixed top-0 left-0 z-5 w-full pt-1">
      <div id="toolbar" class="grid m-toolbar">
        <!-- 网站图标 -->
        <div class="col-2 text-center forum-logo" @click="toHome()">
          <Image alt="网站图标" :width="140" src="https://img.yeziji.xyz/mobile/logger/forum-mobile.png"/>
        </div>
        <!-- 搜索输入框 -->
        <div class="col-8 md:col-7 flex align-items-center justify-content-center text-center"
             @keydown.enter="submitSearch">
          <div class="p-inputgroup">
            <InputText :placeholder="renderValues.placeholder"
                       v-tooltip="renderValues.showTips ? renderValues.defaultTipsContent : ''"
                       v-model="searchText"/>
            <Button icon="pi pi-search"
                    class="p-button-warning"
                    :loading="renderValues.searchLoading"
                    @click="submitSearch"/>
            <Button icon="pi pi-replay"
                    class="p-button-secondary"
                    v-show="renderValues.replayBtnShow"
                    @click="submitReplay"/>
          </div>
        </div>
        <!-- 按钮组 -->
        <div class="col-2 md:col-3 flex align-items-center justify-content-end text-right">
          <Button id="editDetailBtn"
                  class="mr-5 p-button-raised p-button-text"
                  icon="pi pi-pencil" 
                  :label="renderValues.btnText"
                  @click="goEditDetail"/>
          <!-- 用户按钮 -->
          <UserButton ref="userButton"/>
        </div>
        <!-- 标签-->
        <div class="col-12" v-if="renderValues.showTag">
          <div class="inline-block m-1 header__home-tags relative"
               @click="tagClickHandler(item)"
               v-for="(item, index) of tags"
               :key="index">
            <div class="header__tag">{{ item }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
/** JS */
import {ref, Ref, onMounted, watch, inject, defineEmits, defineProps, withDefaults, reactive} from 'vue';
import {useRouter} from 'vue-router';
import {TagService, EasyPageInfo} from '@/utils/ApiRequest';
/** 组件 */
import TagPanel from '@/components/panel/TagPanel.vue';
import UserButton from '../button/UserButton.vue';

interface HeaderToolBarProps {
  searchLoading: boolean
  replayBtnShow: boolean
  showTag: boolean
  showTips: boolean
  placeholder: string
  btnText: string
  defaultTipsContent?: string
  customerEditBtn?: boolean
}

const props = withDefaults(defineProps<HeaderToolBarProps>(), {
  searchLoading: false,
  replayBtnShow: false,
  showTag: true,
  showTips: true,
  placeholder: '搜索文章内容',
  btnText: '发布文章',
  defaultTipsContent: '       普通搜索：文章标题关键字;例：测试数据\n'+
'      专栏搜索：#专栏名称；例：#Java知识点\n'+
'      专栏混合搜索：#专栏名称 文章关键字；例：#Java知识点 认识HashMap\n'+
'      专栏作者搜索：#专栏名称$作者；例：#Java知识点$gzkemays',
  customerEditBtn: false
}), renderValues: HeaderToolBarProps = reactive({
  searchLoading: props.searchLoading,
  replayBtnShow: props.replayBtnShow,
  showTag: props.showTag,
  showTips: props.showTips,
  placeholder: props.placeholder,
  btnText: props.btnText,
  defaultTipsContent: props.defaultTipsContent,
  customerEditBtn: props.customerEditBtn
});

console.log(renderValues)


watch(props, (n) => {
  Object.assign(renderValues, n);
  console.log('watch => ', renderValues)
})
const router = useRouter(),
    tagService = new TagService();
const emits = defineEmits(['submitSearch', 'submitReply', 'clickTag', 'editClick']);
/** 搜索文字 */
let searchText = ref('');
/** 滚动高度 */
let scrollTop = ref(0), oldScrollTop = 0, scrollFixedStatus = ref(true);
/** toolbar div */
let toolbarDom: HTMLElement | undefined | null = undefined,
    editBtn: HTMLElement | undefined | null = undefined,
    userButton = ref(null);
const userButtonAnimate = (isTop: boolean) => {
  const ubref: any = userButton.value;
  if (ubref) {
    let loginBtn = ubref.loginBtn;
    if (loginBtn) {
      loginBtn = loginBtn.$el;
      if (isTop) {
        loginBtn.className += ' ' + 'p-button-text';
      } else {
        if (loginBtn.className.indexOf(' p-button-text') !== -1) {
          loginBtn.className = loginBtn.className.replace(' p-button-text', ' ');
        }
      }
    }
    let notice = ubref.noticeRef;
    if (notice) {
      if (isTop) {
        notice.style.color = '#8B5CF6'
      } else {
        notice.style.color = '#7C3AED'
      }
    }
  }
}
watch(() => scrollTop.value, (newValue, oldValue) => {
  // 必须使用延时器，否则每次newValue和window.scrollY都相等，无法判断，20ms刚好大于watch的侦听周期，故延时20ms
  setTimeout(() => {
    // 意味着置顶
    if (toolbarDom && editBtn) {
      if (newValue === 0) {
        toolbarDom.style['backgroundColor'] = '#eee';
        editBtn.className += ' ' + 'p-button-text';
        userButtonAnimate(true);
      } else {
        toolbarDom.style['backgroundColor'] = '#c27c88';
        if (editBtn.className.indexOf(' p-button-text') !== -1) {
          editBtn.className = editBtn.className.replace(' p-button-text', ' ');
        }
        userButtonAnimate(false);
      }
    }
    if (newValue === window.scrollY) {
      // 延时执行后当newValue等于window.scrollY，代表滚动结束
      oldScrollTop = newValue; // 每次滚动结束后都要给oldScrollTop赋值
    }
  }, 20);
  if (oldScrollTop === oldValue) {
    // 每次滚动开始时oldScrollTop与oldValue相等
    scrollFixedStatus.value = false;
  }
});
/** 点击编辑文章跳转至发布文章的路由页面 */
const goEditDetail = () => {
  if (renderValues.customerEditBtn) {
    // 自定义方法，将 edit detail 事件抛出
    emits('editClick')
  } else {
    router.push({
      path: '/edit',
    })
  }
}
/** 返回主页面 */
const toHome = () => {
  router.push({
    path: '/',
  })
}
/** 标签 */
const tags: Ref<string[]> = ref([]), tagPageInfo: EasyPageInfo = {size: 0, limit: 8};
/** 提交搜索 */
const submitSearch = () => {
      emits('submitSearch', searchText.value);
      searchText.value = '';
    },
    submitReplay = () => {
      emits('submitReply', searchText.value);
    };
/** 点击标签 */
const tagClickHandler = (tag: string) => {
  emits('clickTag', tag);
}

onMounted(() => {
  /** 初始化头部 dom 元素，用于改变样式 */
  toolbarDom = document.getElementById('toolbar'), editBtn = document.getElementById('editDetailBtn');
  /** 监听滚动 */
  window.addEventListener('scroll', () => {
    scrollTop.value = window.scrollY;
  });
  /** 获取标签 */
  tagService.getTagList(tagPageInfo).then((res) => {
    if (res?.data) {
      tags.value = res.data;
    }
  })
})
</script>

<style lang="less">
.forum-logo {
  cursor: pointer;
}

.loginDialog {
  transition: height .3s;
  overflow-x: hidden !important;
}

.register-content {
  padding: 0 1rem 1rem 1rem !important;
}

.p-password {
  .p-inputtext {
    width: 100% !important;
  }
}
</style>